import tkinter as tk
from tkinter import ttk

class FormComponent:
    def __init__(self, parent, defaults=None):
        self.parent = parent
        self.master = parent
        self.fields = []
        self.entries = {}
        self.defaults = defaults or {}

    def text(self, field, label):
        self.fields.append((field, 'text', label))
        return self

    def file(self, field, label):
        self.fields.append((field, 'file', label))
        return self
        
    def dir(self, field, label):
        self.fields.append((field, 'dir', label))
        return self

    def radio(self, field, label, options=None):
        if isinstance(options, dict):
            options = list(options.items())
        self.fields.append((field, 'radio', label, options))
        return self

    def create_form(self):
        for field in self.fields:
            frame = ttk.Frame(self.parent)
            frame.pack(fill='x', pady=5)
            label = ttk.Label(frame, text=field[2])
            label.pack(side='left', padx=5)
            if field[1] == 'file':
                entry = ttk.Entry(frame)
                entry.pack(side='left', expand=True, fill='x', padx=5)
                button = ttk.Button(frame, text='选择文件', command=lambda e=entry: self.select_file(e))
                button.pack(side='right', padx=5)
                self.entries[field[0]] = entry
                if field[0] in self.defaults:
                    entry.insert(0, self.defaults[field[0]])
            elif field[1] == 'dir':
                entry = ttk.Entry(frame)
                entry.pack(side='left', expand=True, fill='x', padx=5)
                open_button = ttk.Button(frame, text='打开目录', command=lambda e=entry: self.open_dir(e))
                open_button.pack(side='right', padx=5)
                button = ttk.Button(frame, text='选择目录', command=lambda e=entry: self.select_dir(e))
                button.pack(side='right', padx=5)
                self.entries[field[0]] = entry
                if field[0] in self.defaults:
                    entry.insert(0, self.defaults[field[0]])
            elif field[1] == 'radio':
                var = tk.StringVar()
                options = field[3] if isinstance(field[3], list) else list(field[3].items())
                for key, value in options:
                    radio = ttk.Radiobutton(frame, text=value, variable=var, value=key)
                    radio.pack(side='left', padx=5)
                self.entries[field[0]] = var
                if field[0] in self.defaults:
                    var.set(self.defaults[field[0]])
            elif field[1] == 'checkout':
                var = tk.StringVar()
                combobox = ttk.Combobox(frame, textvariable=var)
                combobox['values'] = field[3]
                combobox.pack(side='right', expand=True, fill='x', padx=5)
                self.entries[field[0]] = var
                if field[0] in self.defaults:
                    var.set(self.defaults[field[0]])
            elif field[1] == 'checkbox':
                self.entries[field[0]] = {}
                for key, value in field[3].items():
                    var = tk.BooleanVar()
                    checkbox = ttk.Checkbutton(frame, text=value, variable=var)
                    checkbox.pack(side='top', padx=5)
                    self.entries[field[0]][key] = var
                    if field[0] in self.defaults and isinstance(self.defaults[field[0]], dict) and key in self.defaults[field[0]]:
                        var.set(self.defaults[field[0]][key])
            else:
                entry = ttk.Entry(frame)
                entry.pack(side='right', expand=True, fill='x', padx=5)
                self.entries[field[0]] = entry
                if field[0] in self.defaults:
                    entry.insert(0, self.defaults[field[0]])


    def select_file(self, entry):
        from tkinter import filedialog
        file_path = filedialog.askopenfilename(parent=self.master)
        if file_path:
            entry.delete(0, 'end')
            entry.insert(0, file_path)
            
    def select_dir(self, entry):
        from tkinter import filedialog
        dir_path = filedialog.askdirectory()
        if dir_path:
            entry.delete(0, 'end')
            entry.insert(0, dir_path)
            
    def open_dir(self, entry):
        import os
        import subprocess
        dir_path = entry.get()
        if dir_path and os.path.isdir(dir_path):
            try:
                subprocess.Popen(f'explorer "{dir_path}"')
            except Exception as e:
                print(f"打开目录失败: {e}")

    def get_data(self):
        data = {}
        for field, entry in self.entries.items():
            if isinstance(entry, tk.StringVar):
                data[field] = entry.get()
            elif isinstance(entry, dict):
                data[field] = {key: var.get() for key, var in entry.items()}
            else:
                data[field] = entry.get()
        return data

    def submit(self, callback):
        button = ttk.Button(self.parent, text='提交', command=callback)
        button.pack(pady=10)
        return self

    def clear(self):
        for entry in self.entries.values():
            entry.delete(0, 'end')

    def pack(self, **kwargs):
        self.parent.pack(**kwargs)

    def checkout(self, field, label):
        self.fields.append((field, 'checkout', label))
        return self

    def checkbox(self, field, label, options=None):
        self.fields.append((field, 'checkbox', label, options))
        return self

    def add_checkbox_option(self, field, option_label):
        for i, f in enumerate(self.fields):
            if f[0] == field and f[1] == 'checkbox':
                if not f[3]:
                    self.fields[i] = (f[0], f[1], f[2], {})
                self.fields[i][3][option_label] = option_label
        return self

    def option(self, options):
        self.fields[-1] = (*self.fields[-1][:-1], options)
        return self

# 示例使用
if __name__ == '__main__':
    root = tk.Tk()
    # 设置默认值
    defaults = {
        'Name': '张三',
        'Email': 'zhangsan@example.com',
        'Password': '123456',
        'Dir': 'C:/Users/DELL/Videos/虾客/随机ab',
        'Avatar': 'C:/Users/DELL/Videos/虾客/随机ab/20250428183433-c_p.mp4',
        'Type': 'option1',
        'Agree': {'option1': True, 'option2': False}
    }
    form = FormComponent(root, defaults)
    form.text('Name', '姓名')
    form.text('Email', '邮箱')
    form.text('Password', '密码')
    form.file('Avatar', '头像')
    form.dir('Dir', '视频目录')
    form.radio('Type', '类型').option({'option1': '显示视频目录', 'option2': '显示头像'})   
    form.checkbox('Agree', '同意条款').option({'option1': '翻转', 'option2': '扫光'})
    form.create_form()
    def on_submit():
        data = form.get_data()
        print(data)

    form.submit(on_submit)
    root.mainloop()